package com.lxb.mqttdemo

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.Toolbar
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import android.widget.EditText
import android.widget.Toast

import org.eclipse.paho.android.service.MqttAndroidClient
import org.eclipse.paho.client.mqttv3.IMqttActionListener
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken
import org.eclipse.paho.client.mqttv3.IMqttToken
import org.eclipse.paho.client.mqttv3.MqttCallback
import org.eclipse.paho.client.mqttv3.MqttConnectOptions
import org.eclipse.paho.client.mqttv3.MqttException
import org.eclipse.paho.client.mqttv3.MqttMessage

import java.util.ArrayList

class MainActivity : AppCompatActivity() {

    private var mAdapter: HistoryAdapter? = null

    private val clientId = "operator_4"

    private var mqttAndroidClient: MqttAndroidClient? = null

    private val subscriptionTopic = "chat/general" //""test/topic"//"test";

    private var mToolbar: Toolbar? = null
    private var mRecyclerView: RecyclerView? = null
    private var mEditText: EditText? = null
    private var mSendBtn: Button? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        mToolbar = findViewById(R.id.toolbar)
        setSupportActionBar(mToolbar)

        mRecyclerView = findViewById(R.id.history_recycler_view)
        mEditText = findViewById(R.id.editText)
        mSendBtn = findViewById(R.id.button)
        mSendBtn!!.setOnClickListener {
            val txt = mEditText!!.text.toString();
            if (txt.isBlank()) {
                Toast.makeText(applicationContext, "不能为空！！！", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            val msg = MqttMessage(txt.toByteArray())
            mqttAndroidClient!!.publish(subscriptionTopic, msg);
        }

       // val mLayoutManager = LinearLayoutManager(this)
        mRecyclerView!!.layoutManager = LinearLayoutManager(this)

        mAdapter = HistoryAdapter(ArrayList())

        mRecyclerView!!.adapter = mAdapter
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.main_menu, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        if (item!!.itemId == R.id.connect) {
            initMQTT()
            item.isEnabled = false
            return true
        }
        return super.onOptionsItemSelected(item)
    }

    private fun initMQTT() {
        mqttAndroidClient = MqttAndroidClient(applicationContext, serverUri, clientId)
        mqttAndroidClient!!.setCallback(object : MqttCallback {

            override fun connectionLost(cause: Throwable) {
                Log.i(TAG, "Connection lost: ---> ${cause.message}")
                addToHistory("The Connection was lost.")
            }

            @Throws(Exception::class)
            override fun messageArrived(topic: String, message: MqttMessage) {
                message.isRetained
                Log.i(TAG, "topic ---> $topic       message--->$message")
                addToHistory("Incoming message: " + String(message.payload))
            }

            override fun deliveryComplete(token: IMqttDeliveryToken) {
                Log.i(TAG, "token ---> $token")
            }
        })

        val mqttConnectOptions = MqttConnectOptions()

        // 配置MQTT连接
        mqttConnectOptions.isAutomaticReconnect = true
        mqttConnectOptions.isCleanSession = false
        mqttConnectOptions.userName = "admin"
        mqttConnectOptions.password = "password".toCharArray()
        //        mqttConnectOptions.set
        mqttConnectOptions.connectionTimeout = 30  //超时时间
        mqttConnectOptions.keepAliveInterval = 60 //心跳时间,单位秒
        mqttConnectOptions.isAutomaticReconnect = true//自动重连
        //        MqttService
        try {
            mqttAndroidClient!!.connect(mqttConnectOptions, null, object : IMqttActionListener {
                override fun onSuccess(asyncActionToken: IMqttToken) {
                    Toast.makeText(applicationContext, "连接成功", Toast.LENGTH_LONG).show()
                    subscribeToTopic()
                }

                override fun onFailure(asyncActionToken: IMqttToken, exception: Throwable) {
                    addToHistory("Failed to connect to: $serverUri")
                    addToHistory(asyncActionToken.client.clientId)
                    addToHistory(exception.toString())
                }
            })
        } catch (e: MqttException) {
            e.printStackTrace()
        }
    }

    private fun subscribeToTopic() {
        try {
            mqttAndroidClient!!.subscribe(subscriptionTopic, 0, null, object : IMqttActionListener {
                override fun onSuccess(asyncActionToken: IMqttToken) {
                    Log.i(TAG, "Subscribe success ---> $asyncActionToken")
                    addToHistory("Subscribed!")
                }

                override fun onFailure(asyncActionToken: IMqttToken, exception: Throwable) {
                    Log.i(TAG, "Subscribe failure ---> $exception")
                    addToHistory("Failed to subscribe")
                }
            })
        } catch (e: MqttException) {
            Log.i(TAG, "subscribeToTopic is error")
            Log.i(TAG, e.message)
            e.printStackTrace()
        }
    }

    private fun addToHistory(mainText: String) {
        mAdapter!!.add(mainText)
    }

    // 类似于Java中的static 静态变量/方法
    companion object {
        const val serverUri = "tcp://172.16.116.5:61613" //"tcp://211.87.225.235:61613"//"ws://211.87.225.232:3005";
        const val TAG = "MQTT DEMO"
    }
}
